package com.glela.order.service.impl.order;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glela.common.constant.BaseConstants;
import com.glela.common.constant.BaseRestrictionsEnum;
import com.glela.common.constant.CommonConstants;
import com.glela.common.constant.GoodsSelfTypeEnum;
import com.glela.common.constant.GoodsTypeEnum;
import com.glela.common.constant.OpenStoreTypeEnum;
import com.glela.common.constant.OrderStatusEnum;
import com.glela.common.constant.UserJournalStatusEnum;
import com.glela.common.exception.PlatformException;
import com.glela.common.model.ProductTag;
import com.glela.common.util.Config;
import com.glela.common.util.ExtendMethod;
import com.glela.common.util.OrderUtil;
import com.glela.company.model.CompanyXz;
import com.glela.goods.mapper.ShareGoodsMapper;
import com.glela.goods.model.Inventory;
import com.glela.goods.model.LimitTimeSaleDetail;
import com.glela.goods.model.ShareGoods;
import com.glela.goods.model.vo.InventoryVo;
import com.glela.goods.model.vo.StoreVo;
import com.glela.goods.service.LimitTimeSaleDetailService;
import com.glela.goods.service.ShoppingCartService;
import com.glela.order.model.Commision;
import com.glela.order.model.OrderDetail;
import com.glela.order.model.OrderInfo;
import com.glela.order.model.OrderObject;
import com.glela.order.model.OrderSettlement;
import com.glela.order.model.PayTypeConfig;
import com.glela.order.model.request.RequestGetOrderObject;
import com.glela.order.model.request.RequestOrderDetail;
import com.glela.order.model.response.RespAddOrderInfo;
import com.glela.order.model.response.RespGetOrderInfo3;
import com.glela.order.model.vo.order.ErrorMsgGoods;
import com.glela.order.model.vo.order.OrderRecommendAndTeacherVo;
import com.glela.order.model.vo.order.UserWalletVo;
import com.glela.order.service.OrderObjectService;
import com.glela.order.service.OrderTokenService;
import com.glela.order.service.impl.AbstractOrderServiceImpl;
import com.glela.order.service.impl.vo.OrderAddParamsVo;
import com.glela.order.service.impl.vo.OrderVo;
import com.glela.order.util.UserPromotionComparator;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.CUserMoneyChange;
import com.glela.platform.model.CUserPointTransaction;
import com.glela.platform.model.MoneyBusinessType;
import com.glela.platform.model.User;
import com.glela.platform.model.UserAddress;
import com.glela.platform.model.UserInfo;
import com.glela.platform.model.UserJournal;
import com.glela.platform.model.UserPayInfo;
import com.glela.platform.model.UserPointJournal;
import com.glela.platform.model.UserPromotion;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.service.UserPayInfoService;
import com.glela.platform.vo.GoodsSimpleVo;
import com.glela.platform.vo.UserPromotionVo;

@Service("orderService4")
@Order(4)
@Deprecated
/** 历史版本 */
public class OrderServiceImpl4 extends AbstractOrderServiceImpl {
	private static Logger				logger	= LoggerFactory.getLogger(OrderServiceImpl4.class);
	@Autowired
	private OrderObjectService			orderObjectService;
	@Autowired
	private ShoppingCartService			shoppingCartService;
	@Autowired
	private OrderTokenService			orderTokenService;
	@Autowired
	private LimitTimeSaleDetailService	limitTimeSaleDetailService;
	@Autowired
	private UserPayInfoService			userPayInfoService;

	@Override
	public ResponseResultModel<RespGetOrderInfo3> getToOrderInfo(RequestGetOrderObject requestGetOrderObject) {
		DateTime nowTime = new DateTime();//当前时间，以次时间为去结算开始时间点
		/*初始化返回结果*/
		RespGetOrderInfo3 respGetOrderInfo = new RespGetOrderInfo3();
		respGetOrderInfo.setToken(requestGetOrderObject.getToken());

		List<GoodsSimpleVo> _avl_goods_list = new LinkedList<GoodsSimpleVo>();
		List<ErrorMsgGoods> _err_goods_list = new LinkedList<ErrorMsgGoods>();

		ResponseResultModel<RespGetOrderInfo3> resultModel = new ResponseResultModel<RespGetOrderInfo3>(ErrorEnum.C10000, respGetOrderInfo);

		/*校验基础信息合法性*/
		//当前登录人信息
		Long _login_user_id = requestGetOrderObject.getUserId();
		ResponseUser _login_user = userService.selectUserRoleById(_login_user_id);
		if (_login_user == null || _login_user.getUserId() == null) {
			resultModel.setError(ErrorEnum.C20111);
			resultModel.setMessage("用户信息异常，请联系客服处理");
			logger.error("登录用户{}无效-{}", _login_user_id, JSONObject.toJSONString(_login_user));
			return resultModel;
		}
		ResponseUser _store_user = userService.selectUserRoleByPersonId(_login_user.getRecommendFrom());
		if (_check_login_user(_login_user, _store_user, resultModel)) {
			return resultModel;
		}

		//购买商品明细
		List<GoodsSimpleVo> _req_product_list = requestGetOrderObject.getGoodsSimpleVoList();
		if (CollectionUtils.isEmpty(_req_product_list)) {
			resultModel.setError(ErrorEnum.C20701);
			return resultModel;
		}
		//用户提交的购买商品信息（以库存id为主键归类）
		Map<Long, GoodsSimpleVo> _req_goods_map = new HashMap<Long, GoodsSimpleVo>();
		int i = 0;
		long _talentId = 0;
		for (GoodsSimpleVo req_goods : _req_product_list) {
			if (req_goods.getQuantity() < 1) {
				resultModel.setError(ErrorEnum.C20701);
				resultModel.setMessage("购买数量必须大于等于1");
				return resultModel;
			}
			if (i++ == 0) {
				_talentId = req_goods.getTalentId();
			} else if (req_goods.getTalentId() > 0 && req_goods.getTalentId() != _talentId) {//一笔交易只允许出现一个分享人
				resultModel.setError(ErrorEnum.C20780);
				resultModel.setMessage("分享商品每次只能购买同一个分享人的产品");
				return resultModel;
			}
			req_goods.setApplywelfareId(0);
			req_goods.setActivityType(0);
			//过滤失效商品
			if (_check_share_goods_and_talent(req_goods, resultModel)) {
				return resultModel;
			}

			if (req_goods.getInventoryId() < 1) {
				resultModel.setError(ErrorEnum.C20102);
				return resultModel;
			} else if (_req_goods_map.containsKey(req_goods.getInventoryId())) {
				resultModel.setError(ErrorEnum.C20133);
				return resultModel;
			} else {
				_req_goods_map.put(req_goods.getInventoryId(), req_goods);
			}
		}
		if (_req_product_list.size() != _req_goods_map.size()) {
			resultModel.setError(ErrorEnum.C20133);
			return resultModel;
		}

		/*计算商品库存、价格*/
		List<GoodsSimpleVo> _check_goods_list = orderDao.selectGetOrderGoodsInfo(_req_product_list);
		//		Map<Long, GoodsSimpleVo> _check_goods_map = new HashMap<Long, GoodsSimpleVo>();

		long _xz_sister_user_id = BaseConstants.XZ_SISTER;
		int _total_open_goods_total_amount = 0;//总开店商品销售价
		long _total_prod = 0;//商品总数量
		long _gain_xzb = 0;//获得妆币|有效商品
		OrderVo _prom = new OrderVo(_login_user_id);

		for (GoodsSimpleVo goodsSimpleVo : _check_goods_list) {
			if (goodsSimpleVo.getGoodsType() != GoodsTypeEnum.T1.getCode()) {
				resultModel.setError(ErrorEnum.C20807);
				resultModel.setMessage("只能购买B区商品");
				return resultModel;
			}
			try {
				if (goodsSimpleVo.getOnlineTime() == null || goodsSimpleVo.getOfflineTime() == null || goodsSimpleVo.getOnlineTime().getTime() - nowTime.getMillis() > 0 || goodsSimpleVo.getOfflineTime().getTime() - nowTime.getMillis() < 0) {
					_err_goods_list.add(_pack_error_msg_goods(goodsSimpleVo, ErrorEnum.C20401.getMessage()));
					continue;
				}
			} catch (Exception e) {
				_err_goods_list.add(_pack_error_msg_goods(goodsSimpleVo, ErrorEnum.C20401.getMessage()));
				continue;
			}
			Inventory _check_inventory = inventoryMapper.selectByPrimaryKey(goodsSimpleVo.getInventoryId());
			if (_check_inventory == null || _check_inventory.getStatus() != 1) {//无库存
				_err_goods_list.add(_pack_error_msg_goods(goodsSimpleVo, "无库存"));
				continue;
			}

			int _check_sale_price = 0;
			int _check_product_inventory_num = 0;
			GoodsSimpleVo _req_goods = _req_goods_map.get(goodsSimpleVo.getInventoryId());

			if (_req_goods == null || _check_inventory.getGoodId() != _req_goods.getGoodId()) {
				_err_goods_list.add(_pack_error_msg_goods(goodsSimpleVo, "商品已离家出走，暂时无法购买"));
				logger.error("下单商品与数据库数据出现不一致：{}", JSONObject.toJSONString(goodsSimpleVo));
				continue;
			}

			//判断商品是否为分时抢购商品
			LimitTimeSaleDetail _check_limit_time_sale_detail = limitTimeSaleDetailService.queryByProductId(goodsSimpleVo.getProductId(), nowTime.toDate());
			//判断库存、判断售价
			if (_check_limit_time_sale_detail == null) {
				long _price_user_id = _store_user.getUserId();
				if (_req_goods.getTalentId() > 0) {
					User _check_talent_store_user = userService.selectRecommendFromByUserId(_req_goods.getTalentId());
					if (_check_talent_store_user == null) {
						resultModel.setError(ErrorEnum.C20111);
						resultModel.setMessage("分享人无效");
						return resultModel;
					} else {
						_price_user_id = _check_talent_store_user.getId();
					}
				}

				if (_price_user_id == _xz_sister_user_id) {// 当前登录人的推荐人为： 校妆姐姐，所以取校妆姐姐价
					_check_sale_price = _check_inventory.getXzSalePrice();
				} else {// 当前登录人的推荐人为： 一般店主，所以取店主价
					_check_sale_price = _check_inventory.getSalePrice();
				}
				_check_product_inventory_num = _check_inventory.getInventoryNum();
			} else {
				_check_sale_price = _check_limit_time_sale_detail.getProductSalePrice();
				goodsSimpleVo.getProductTags().add(new ProductTag());
				//校验分时抢购数量
				if (_check_limit_time_sale_detail.getSkuCount().intValue() < _req_goods.getQuantity()) {//总限购数
					_err_goods_list.add(_pack_error_msg_goods(goodsSimpleVo, "超过限购数"));
					continue;
				} else {//用户限购数
							//查询已购数（包含待支付,待发货,待收货,已完成,交易成功,交易关闭）
					Integer limitSaleNums = this.orderDetailMapper.selectLimitSaleNums(_login_user.getUserId(), _check_limit_time_sale_detail.getLimitTimeSaleId(), goodsSimpleVo.getProductId(), goodsSimpleVo.getInventoryId());
					if (limitSaleNums != null && (limitSaleNums + _req_goods.getQuantity() > _check_limit_time_sale_detail.getUserSkuCount())) {
						_err_goods_list.add(_pack_error_msg_goods(goodsSimpleVo, "超过每人限购数"));
						continue;
					}
				}

				if (_check_inventory.getInventoryNum() <= _check_limit_time_sale_detail.getSkuCount()) {
					_check_product_inventory_num = _check_inventory.getInventoryNum();
				} else {
					_check_product_inventory_num = _check_limit_time_sale_detail.getSkuCount();
				}
			}
			if (_req_goods.getQuantity() > _check_product_inventory_num) {//无库存
				_err_goods_list.add(_pack_error_msg_goods(goodsSimpleVo, "库存不足"));
				continue;
			}

			goodsSimpleVo.setSalePrice(_check_sale_price);
			if (_check_sale_price != _req_goods.getSalePrice()) {//价格不等
				goodsSimpleVo.setSalePriceDesc((_check_sale_price < _req_goods.getSalePrice() ? "已降￥" : "已涨￥") + ((_check_sale_price - _req_goods.getSalePrice()) / 100.0));
			}

			//封装前端提交的商品信息
			goodsSimpleVo.setQuantity(_req_goods.getQuantity());
			goodsSimpleVo.setTalentSerialId(_req_goods.getTalentSerialId());
			goodsSimpleVo.setTalentShareGoodId(_req_goods.getTalentShareGoodId());
			goodsSimpleVo.setTalentId(_req_goods.getTalentId());

			if (_req_goods.getSalePrice() <= 0 || _check_sale_price <= 0) {
				logger.error("商品[{}-{}]销售价格小于等于0[{},{}] 请求报文：{}", goodsSimpleVo.getGoodId(), goodsSimpleVo.getProductId(), _check_sale_price, _req_goods.getSalePrice(), JSONObject.toJSONString(requestGetOrderObject));
				resultModel.setError(ErrorEnum.C20701);
				resultModel.setMessage("购买商品已下架");
				return resultModel;
			}

			//记录有效商品
			_avl_goods_list.add(goodsSimpleVo);
			//商品总金额
			int _prod_total_amount = _check_sale_price * goodsSimpleVo.getQuantity();
			//设置订单相关汇总信息
			_prom.setValue(_prod_total_amount, goodsSimpleVo.getStoreId(), goodsSimpleVo.getSelfSupport(), goodsSimpleVo.getGoodId(), goodsSimpleVo.getBrandId());
			_total_prod += goodsSimpleVo.getQuantity();
			//可获得妆币
			if (goodsSimpleVo.getScoreRate() > 0) {
				_gain_xzb += goodsSimpleVo.getScoreRate() * _prod_total_amount;
			}

			//开店产品累计开店金额
			if (goodsSimpleVo.isOpenGoods()) {//累计开店商品金额
				if (!_login_user.isStoreLevel()) {//不是店主累加商品总价
					_total_open_goods_total_amount += _prod_total_amount;
				}
			}
		}

		respGetOrderInfo.setTotalProd(_total_prod);
		respGetOrderInfo.setTotalPrice(_prom.getTotalPrice());
		respGetOrderInfo.setAcquirableXzb(_gain_xzb);
		respGetOrderInfo.getGoodsSimpleVoList().addAll(_avl_goods_list);
		respGetOrderInfo.getErrorMsg().getInvalidGoods().addAll(_err_goods_list);
		//		respGetOrderInfo.getErrorMsg().getAvlGoods().addAll(_avl_goods_list);

		if (CollectionUtils.isEmpty(_avl_goods_list)) {
			return resultModel;
		}
		//校验分佣关系
		if (_check_commission_relationship(_avl_goods_list.get(0).getTalentId(), _avl_goods_list.size(), _login_user, null, resultModel)) {
			return resultModel;
		}

		if (!_login_user.isStoreLevel()) {
			BaseRestrictions _open_store_self_fee = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.T6.getText());
			if (_open_store_self_fee == null) {
				resultModel.setError(ErrorEnum.C20000);
				resultModel.setMessage("缺少开店配置");
				return resultModel;
			} else {
				if (_open_store_self_fee.getRestrictions() <= _total_open_goods_total_amount) {
					//校验是否已经有开店单
					List<OrderObject> _check_open_store_order_list = orderDao.selectOpenOrder(_login_user_id);
					if (CollectionUtils.isNotEmpty(_check_open_store_order_list)) {
						resultModel.setError(ErrorEnum.C21201);
						resultModel.setMessage("您已经下过开店订单，请完成或取消之前待付款订单");
						return resultModel;
					}
					_prom.clear();
					_gain_xzb = 0;
					//开店单打折
					for (GoodsSimpleVo valGoods : _avl_goods_list) {
						//						if (valGoods.getSelfSupport() == GoodsSelfTypeEnum.T0.getCode() && valGoods.getGoodsType() == GoodsTypeEnum.T1.getCode()) {
						if (valGoods.isOpenGoods()) {
							valGoods.setSalePrice(valGoods.getSalePrice() * _open_store_self_fee.getExperience() / 100);
							GoodsSimpleVo _req_goods = _req_goods_map.get(valGoods.getInventoryId());
							if (valGoods.getSalePrice() != _req_goods.getSalePrice()) {
								valGoods.setSalePriceDesc("首单礼" + (valGoods.getSalePrice() < _req_goods.getSalePrice() ? "已降￥" : "已涨￥") + ((valGoods.getSalePrice() - _req_goods.getSalePrice()) / 100.0));
							}
						}
						_prom.setValue(valGoods.getSalePrice() * valGoods.getQuantity(), valGoods.getStoreId(), valGoods.getSelfSupport(), valGoods.getGoodId(), valGoods.getBrandId());
						if (valGoods.getScoreRate() > 0) {
							_gain_xzb += valGoods.getSalePrice() * valGoods.getQuantity() * valGoods.getScoreRate();
						}
					}
					respGetOrderInfo.setTotalPrice(_prom.getTotalPrice());
					respGetOrderInfo.setAcquirableXzb(_gain_xzb);
				}
			}
		}
		//计算可用优惠券
		respGetOrderInfo.getUserPromotionList().addAll(selcetAvlProm(_prom));
		//计算运费
		BaseRestrictions _check_freight_restriction = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.FULL_FREE_FREIGHT);
		if (_check_freight_restriction != null && _check_freight_restriction.getRestrictions() > respGetOrderInfo.getTotalPrice()) {
			respGetOrderInfo.setFreight(_check_freight_restriction.getExperience());
		} else {
			respGetOrderInfo.setFreight(_get_default_freight());
		}
		//		respGetOrderInfo.setPayTypeConfigList(getPayType());
		respGetOrderInfo.setPayable(true);
		respGetOrderInfo.setUserMoney(getUserWallet(_login_user_id));
		respGetOrderInfo.getUserMoney().setHasPayPwd(userPayInfoService.existsPwd(_login_user_id));
		orderTokenService.addToken(respGetOrderInfo.getToken(), _login_user_id);
		_prom = null;
		return resultModel;
	}

	@Override
	public ResponseResultModel<RespAddOrderInfo> addOrderInfo(RequestOrderDetail reqOrderDetail) throws PlatformException {
		DateTime nowTime = new DateTime();//当前时间，以次时间为去结算开始时间点
		RespAddOrderInfo respAddOrderInfo = new RespAddOrderInfo();
		List<OrderDetail> _avl_goods_list = new LinkedList<OrderDetail>();
		List<ErrorMsgGoods> _err_goods_list = new LinkedList<ErrorMsgGoods>();
		ResponseResultModel<RespAddOrderInfo> resultModel = new ResponseResultModel<RespAddOrderInfo>(ErrorEnum.C10000, respAddOrderInfo);

		//当前登录人信息
		Long _login_user_id = reqOrderDetail.getUserId();
		ResponseUser _login_user = userService.selectUserRoleById(_login_user_id);
		if (_login_user == null || _login_user.getUserId() == null) {
			resultModel.setError(ErrorEnum.C20111);
			return resultModel;
		}
		ResponseUser _store_user = userService.selectUserRoleByPersonId(_login_user.getRecommendFrom());
		if (_check_login_user(_login_user, _store_user, resultModel)) {
			return resultModel;
		}
		UserWalletVo _log_user_money = getUserWallet(_login_user_id);
		if (_check_avail_req_get_order_obj(reqOrderDetail, resultModel, _log_user_money)) {
			return resultModel;
		}
		respAddOrderInfo.setUserMoney(_log_user_money);
		//		//用户现金币不能超额支付
		//		if (_login_user.getMoney().longValue() < reqOrderDetail.getCashCoin()) {
		//			resultModel.setError(ErrorEnum.C20125);
		//			return resultModel;
		//		}
		List<OrderDetail> _req_order_detail_list = reqOrderDetail.getOrderDetailList();
		//购买商品明细
		if (CollectionUtils.isEmpty(_req_order_detail_list)) {
			resultModel.setError(ErrorEnum.C20701);
			return resultModel;
		}
		//用户配送地址
		UserAddress userAddress = userAddressService.selectUserAddressById(reqOrderDetail.getMemberDeliveryAddressId());
		if (userAddress == null) {
			resultModel.setError(ErrorEnum.C20129);
			return resultModel;
		}

		//如果商品归属分类 （1.正常2.福利社 3体验）为空，默认为0
		if (_req_order_detail_list.get(0).getApplywelfareId() == null) {
			_req_order_detail_list.get(0).setApplywelfareId(0);
		}
		Map<Long, InventoryVo> _check_inventory_map = new HashMap<Long, InventoryVo>();
		createInventoryMap(_check_inventory_map, _req_order_detail_list);

		long _xz_sister_user_id = BaseConstants.XZ_SISTER;
		int _total_open_goods_sale_price = 0;//总开店商品销售价
		//		Map<Integer, Integer> openStoreSelfFeeMap = new HashMap<Integer, Integer>();//B区店铺自有商品应付总金额,
		int _diff_total_price = 0;//价格变动差价综合
		int k = 0;
		long _talentId = 0;
		long _gain_xzb = 0;//获得妆币|有效商品
		OrderAddParamsVo orderVo = new OrderAddParamsVo(_login_user_id);
		String _now_time = ExtendMethod.getCurrentDateTime();
		long nowTimeMillis = nowTime.getMillis();

		for (OrderDetail _req_order_detail : _req_order_detail_list) {
			if (_req_order_detail.getQuantity() == null || _req_order_detail.getQuantity().intValue() < 1) {
				resultModel.setError(ErrorEnum.C20701);
				resultModel.setMessage("购买数量必须大于等于1");
				return resultModel;
			}
			_req_order_detail.setUserId(_login_user.getUserId());
			if (k++ == 0) {
				_talentId = _req_order_detail.getTalentId() == null ? 0 : _req_order_detail.getTalentId();
			} else if (_req_order_detail.getTalentId() != null && _req_order_detail.getTalentId().longValue() > 0 && _req_order_detail.getTalentId().longValue() != _talentId) {
				//每笔交易只允许出现一个分享人
				resultModel.setError(ErrorEnum.C20780);
				resultModel.setMessage("分享商品每次只能购买同一个分享人的产品");
				return resultModel;
			}

			/*校验*/
			if (_check_share_goods_and_talent(_req_order_detail.getGoodId(), _req_order_detail.getTalentId(), _req_order_detail.getTalentShareGoodId(), resultModel)) {
				_check_inventory_map.remove(_req_order_detail.getInventoryId());
				return resultModel;
			}

			InventoryVo _check_inventory = _check_inventory_map.get(_req_order_detail.getInventoryId());
			if (_check_inventory == null || _check_inventory.getStatus() != 1 || _check_inventory.getInventoryNum() <= 0) {
				_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, "库存不足"));
				_check_inventory_map.remove(_req_order_detail.getInventoryId());
				continue;
			}
			if (_check_inventory.getId() != _req_order_detail.getInventoryId() || _check_inventory.getProductId() != _req_order_detail.getProductId() || _check_inventory.getGoodId() != _req_order_detail.getGoodId()) {
				_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, "库存不足"));
				_check_inventory_map.remove(_req_order_detail.getInventoryId());
				continue;
			}

			//			_check_inventory.setApplywelfareId(0);
			//			_req_order_detail.setApplywelfareId(0);
			_req_order_detail.setActivityType(0);
			_req_order_detail.setIsOpenStoreGoods(_check_inventory.isOpenGoods() ? 1 : 0);

			//1：b、c区商品不能一同支付
			if (_check_inventory.getGoodsType() != GoodsTypeEnum.T1.getCode()) {
				_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, "只能购买B区商品"));
				_check_inventory_map.remove(_req_order_detail.getInventoryId());
				continue;
			}
			//2：下单商品必须上架可售
			if (_check_inventory.isNotOnTheShelf(nowTimeMillis)) {
				_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, ErrorEnum.C20401.getMessage()));
				_check_inventory_map.remove(_req_order_detail.getInventoryId());
				continue;
			}

			int _check_sale_price = 0;
			int _check_product_inventory_num = 0;

			//判断商品是否为分时抢购商品
			LimitTimeSaleDetail _check_limit_time_sale_detail = limitTimeSaleDetailService.queryByProductId(_check_inventory.getProductId(), nowTime.toDate());
			//判断库存、判断售价
			if (_check_limit_time_sale_detail == null) {
				long _price_user_id = _store_user.getUserId();
				if (_req_order_detail.getTalentId() > 0) {
					User _check_talent_store_user = userService.selectRecommendFromByUserId(_req_order_detail.getTalentId());
					if (_check_talent_store_user == null) {
						resultModel.setError(ErrorEnum.C20111);
						resultModel.setMessage("分享人无效");
						return resultModel;
					} else {
						_price_user_id = _check_talent_store_user.getId();
					}
				}

				if (_price_user_id == _xz_sister_user_id) {// 当前登录人的推荐人为： 校妆姐姐，所以取校妆姐姐价
					_check_sale_price = _check_inventory.getXzSalePrice();
				} else {// 当前登录人的推荐人为： 一般店主，所以取店主价
					_check_sale_price = _check_inventory.getSalePrice();
				}
				_check_product_inventory_num = _check_inventory.getInventoryNum();
			} else {
				_req_order_detail.setLimitTimeSaleId(_check_limit_time_sale_detail.getLimitTimeSaleId());
				_req_order_detail.setLimitTimeSaleDetailId(_check_limit_time_sale_detail.getId());
				_check_sale_price = _check_limit_time_sale_detail.getProductSalePrice();

				//校验分时抢购数量
				if (_check_limit_time_sale_detail.getSkuCount().intValue() < _req_order_detail.getQuantity()) {//总限购数
					_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, "超过限购数"));
					continue;
				} else {//用户限购数
							//查询已购数（包含待支付,待发货,待收货,已完成,交易成功,交易关闭）
					Integer limitSaleNums = this.orderDetailMapper.selectLimitSaleNums(_login_user.getUserId(), _check_limit_time_sale_detail.getLimitTimeSaleId(), _check_inventory.getProductId(), _check_inventory.getId());
					if (limitSaleNums != null && limitSaleNums + _req_order_detail.getQuantity() > _check_limit_time_sale_detail.getUserSkuCount()) {
						_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, "超过每人限购数"));
						continue;
					}
				}

				if (_check_inventory.getInventoryNum() <= _check_limit_time_sale_detail.getSkuCount()) {
					_check_product_inventory_num = _check_inventory.getInventoryNum();
				} else {
					_check_product_inventory_num = _check_limit_time_sale_detail.getSkuCount();
				}
			}
			if (_req_order_detail.getQuantity() > _check_product_inventory_num) {//无库存
				_err_goods_list.add(_pack_error_msg_goods(_req_order_detail, "库存不足"));
				_check_inventory_map.remove(_req_order_detail.getInventoryId());
				continue;
			}

			if (_check_sale_price != _req_order_detail.getSalePrice()) {//价格不等
				int _diff_sale_price = _check_sale_price - _req_order_detail.getSalePrice();
				_diff_total_price += _diff_sale_price * _req_order_detail.getQuantity();
				_req_order_detail.setSalePriceDesc((_diff_sale_price < 0 ? "降价" : "涨价") + "￥" + (_diff_sale_price / 100d));
			}
			//			_req_order_detail.setSalePrice(_check_sale_price);
			_check_inventory.setSalePrice(_check_sale_price);

			//			if (_check_inventory.getSelfSupport() == GoodsSelfTypeEnum.T0.getCode() && _req_order_detail.getGoodsType() == GoodsTypeEnum.T1.getCode()) {//b区自营商品
			if (_check_inventory.isOpenGoods()) {
				if (!_login_user.isStoreLevel()) {//不是店主累计商品销售额
					_total_open_goods_sale_price += _check_inventory.getSalePrice() * _req_order_detail.getQuantity();
					//					if (openStoreSelfFeeMap.get(_req_order_detail.getStoreId()) == null) {
					//						openStoreSelfFeeMap.put(_req_order_detail.getStoreId(), _check_inventory.getSalePrice() * _req_order_detail.getQuantity());
					//					} else {
					//						openStoreSelfFeeMap.put(_req_order_detail.getStoreId(), openStoreSelfFeeMap.get(_req_order_detail.getStoreId()) + _check_inventory.getSalePrice() * _req_order_detail.getQuantity());
					//					}
				}
			}
			if (_req_order_detail.getSalePrice() <= 0 || _check_sale_price <= 0) {
				logger.error("商品[{}-{}]销售价格小于等于0[{},{}] 请求报文：{}", _check_inventory.getGoodId(), _check_inventory.getProductId(), _check_sale_price, _req_order_detail.getSalePrice(), JSONObject.toJSONString(reqOrderDetail));
				resultModel.setError(ErrorEnum.C20701);
				resultModel.setMessage("购买商品已下架");
				return resultModel;
			}

			_req_order_detail.setBrandId(_check_inventory.getBrandId());
			_req_order_detail.setStoreId(_check_inventory.getStoreId());
			_req_order_detail.setSelfSupport(_check_inventory.getSelfSupport());
			_req_order_detail.setGoodsType(_check_inventory.getGoodsType());

			_avl_goods_list.add(_req_order_detail);

			orderVo.setValue(_check_sale_price, _check_inventory.getSettlementPrice(), _req_order_detail.getQuantity(), _check_inventory.getStoreId(), _check_inventory.getSelfSupport(), _check_inventory.getGoodId(), _check_inventory.getBrandId(), _req_order_detail, _check_inventory);

			if (_check_inventory.getScoreRate() > 0) {
				_gain_xzb += _check_inventory.getScoreRate() * _req_order_detail.getQuantity().intValue() * _check_inventory.getSalePrice();
			}
		}
		respAddOrderInfo.getErrorMsg().getInvalidGoods().clear();
		respAddOrderInfo.getErrorMsg().getInvalidGoods().addAll(_err_goods_list);
		respAddOrderInfo.setTotalProd(orderVo.getTotalQuantity());
		respAddOrderInfo.setAcquirableXzb(_gain_xzb);
		respAddOrderInfo.setTotalPrice(orderVo.getTotalPrice());

		//是否是首单
		//获取开店订单优惠比例且标注此单是否为开店单
		int isOpenStore = 0;
		int experience = 0;//开店单打折比例（百分制）
		Map<String, BaseRestrictions> baseRestrictionsMap = selectAllBaseRestrictions();
		BaseRestrictions baseRestrictionsForCache = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.T6);
		if (baseRestrictionsForCache == null || baseRestrictionsForCache.getExperience() <= 0 || baseRestrictionsForCache.getRestrictions() < 0) {
			resultModel.setError(ErrorEnum.C20107);
			logger.error("系统常量配置异常：{}", BaseRestrictionsEnum.T6.getText());
			return resultModel;
		}
		experience = baseRestrictionsForCache.getExperience();
		if (_total_open_goods_sale_price >= baseRestrictionsForCache.getRestrictions()) {//满足开店条件
			isOpenStore = 1;//标识开店单
			if (experience != 100) {//开店优惠
				//销售价打折
				_diff_total_price = 0;
				_gain_xzb = 0;
				orderVo.clear();
				for (OrderDetail orderDetail : _avl_goods_list) {
					InventoryVo _check_inventory = _check_inventory_map.get(orderDetail.getInventoryId());
					if (_check_inventory.isOpenGoods()) {
						_check_inventory.setSalePrice(_check_inventory.getSalePrice() * experience / 100);
						int _diff_sale_price = _check_inventory.getSalePrice() - orderDetail.getSalePrice();
						_diff_total_price += _diff_sale_price * orderDetail.getQuantity().intValue();
						orderDetail.setSalePriceDesc("开店商品" + (_diff_sale_price < 0 ? "降价" : "涨价") + "￥" + (_diff_sale_price / 100d));
						orderDetail.setSalePrice(_check_inventory.getSalePrice());
					}
					if (_check_inventory.getScoreRate() > 0) {
						_gain_xzb += _check_inventory.getScoreRate() * orderDetail.getQuantity().intValue() * _check_inventory.getSalePrice();
					}
					orderVo.setValue(_check_inventory.getSalePrice(), _check_inventory.getSettlementPrice(), orderDetail.getQuantity(), orderDetail.getSelfSupport(), orderDetail.getStoreId(), orderDetail.getGoodId(), orderDetail.getBrandId(), orderDetail, _check_inventory);
				}
				respAddOrderInfo.setAcquirableXzb(_gain_xzb);
				respAddOrderInfo.setTotalPrice(orderVo.getTotalPrice());
			}
		}

		if (_diff_total_price != 0) {
			if (_diff_total_price < 0) {
				respAddOrderInfo.getErrorMsg().setDesPriceChanger("商品价格发生变动，累计降价￥" + (_diff_total_price / 100d));
			} else {
				respAddOrderInfo.getErrorMsg().setDesPriceChanger("商品价格发生变动，累计涨价￥" + (_diff_total_price / 100d));
			}
			if (CollectionUtils.isNotEmpty(_avl_goods_list)) {
				for (OrderDetail orderDetail : _req_order_detail_list) {
					if (isOpenStore == 0) {
						InventoryVo _check_inventory = _check_inventory_map.get(orderDetail.getInventoryId());
						orderDetail.setSalePrice(_check_inventory.getSalePrice());
					}
				}
			}
			respAddOrderInfo.getErrorMsg().getAvlGoods().clear();
			respAddOrderInfo.getErrorMsg().getAvlGoods().addAll(_avl_goods_list);
			respAddOrderInfo.setTotalPrice(orderVo.getTotalPrice());
			return resultModel;
		}
		respAddOrderInfo.getErrorMsg().getAvlGoods().clear();
		respAddOrderInfo.getErrorMsg().getAvlGoods().addAll(_avl_goods_list);
		if (CollectionUtils.isNotEmpty(_err_goods_list) || CollectionUtils.isEmpty(_avl_goods_list)) {
			return resultModel;
		}

		String recommendFrom = BaseConstants.XZ_SISTER_PERSION_ID;//推荐人身份ID
		String talentTeacher = "";//达人导师/经纪人身份id
		OrderRecommendAndTeacherVo orderRecommendAndTeacherVo = new OrderRecommendAndTeacherVo();
		if (_check_commission_relationship(_avl_goods_list.get(0).getTalentId(), _avl_goods_list.size(), _login_user, orderRecommendAndTeacherVo, resultModel)) {
			return resultModel;
		} else {
			recommendFrom = orderRecommendAndTeacherVo.getRecommendFrom();
			talentTeacher = orderRecommendAndTeacherVo.getTalentTeacher();
		}

		/*优惠券*/
		UserPromotionVo userPromotion = null;
		if (reqOrderDetail.getPromotionId() > 0) {
			List<UserPromotionVo> selcetAvlProm = selcetAvlProm(orderVo);
			for (UserPromotionVo userPromotionVo : selcetAvlProm) {
				if (userPromotion != null) {
					break;
				}
				if (userPromotionVo.getPromotionDetailId() == reqOrderDetail.getPromotionId()) {
					userPromotion = userPromotionVo;
				}
			}
			if (userPromotion == null || userPromotion.getPromotionNumber() <= 0 || (userPromotion.getType() == 7 && (userPromotion.getTargetSelfType() == GoodsSelfTypeEnum.T0.getCode() && orderVo.isHasNoSelfGoods() && userPromotion.getTargetSelfType() == GoodsSelfTypeEnum.T1.getCode() && orderVo.isHasSelfGoods()))) {
				logger.warn("下单用户{}优惠券{}不可用 {}", _login_user_id, reqOrderDetail.getPromotionId(), JSONObject.toJSONString(reqOrderDetail));
				resultModel.setError(ErrorEnum.C30110);
				return resultModel;
			}
		}

		/*活动*/
		/*事务回滚开始*/
		if (!orderTokenService.removeToken(reqOrderDetail.getToken())) {//防重复提交
			resultModel.setError(ErrorEnum.C20001);
			logger.error("用户:{}生成订单token重复:{}-{}", reqOrderDetail.getUserId(), reqOrderDetail.getToken(), JSON.toJSONString(reqOrderDetail));
			return resultModel;
		}
		/*生成交易单*/
		if (reqOrderDetail.getPromotionId() > 0) {//使用优惠券
			//FIXME 查找前端提交优惠券信息，但未对此优惠券有效性进行验证
			int upResult = userPromotionService.updateSubUserPromotionNumber(reqOrderDetail.getPromotionId(), _login_user.getUserId());
			if (upResult != 1) {//FIXME 优惠券未使用，没有将优惠券置空，后续代码又根据此优惠券进行处理
				logger.error("用户" + _login_user.getUserId() + "的优惠券" + reqOrderDetail.getPromotionId() + "不可用");
				throw new PlatformException(ErrorEnum.C30110, "优惠券不可用");
			}
		}

		OrderObject addOrderObj = new OrderObject();
		addOrderObj.setOpenStore(isOpenStore);//累计开店及购买了开店商品，标记开店单

		//生成交易单号
		StringBuffer orderSn = new StringBuffer();
		orderSn.append(CommonConstants.ORDER_OBJECT_PREFIX).append(OrderUtil.getOrderSn());
		addOrderObj.setOrderSn(orderSn.toString());
		respAddOrderInfo.setOrderSn(addOrderObj.getOrderSn());

		//生产父单
		createOrderObj(addOrderObj, reqOrderDetail, userAddress);
		addOrderObj.setUserId(_login_user_id);//当前购买人
		addOrderObj.setTotalPrice(orderVo.getTotalPrice());//设置总销售金额
		if (userPromotion == null) {
			addOrderObj.setPromotionDiscount(0);
		} else {
			addOrderObj.setPromotionDiscount((int) userPromotion.getDiscountAmount());
		}
		//运费
		//设置运费
		BaseRestrictions freightRts = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.FULL_FREE_FREIGHT);
		if (freightRts != null && freightRts.getRestrictions() > addOrderObj.getTotalPrice().intValue()) {
			addOrderObj.setFreight(freightRts.getExperience());
		} else {
			addOrderObj.setFreight(_get_default_freight());
		}
		//优惠不参与运费抵扣，单独计算
		if (addOrderObj.getPromotionDiscount().intValue() > 0) {//有优惠，减掉优惠等于实付现金
			addOrderObj.setTotalFee(addOrderObj.getTotalPrice().intValue() - addOrderObj.getPromotionDiscount().intValue());
			//实付现金小于0，多抵扣的部分从优惠中扣除，实付现金设置为0
			if (addOrderObj.getTotalFee().intValue() < 0 && addOrderObj.getTotalFee().intValue() + addOrderObj.getPromotionDiscount() >= 0) {
				addOrderObj.setPromotionDiscount(addOrderObj.getPromotionDiscount().intValue() + addOrderObj.getTotalFee());
				userPromotion.setDiscountAmount(addOrderObj.getPromotionDiscount());
				addOrderObj.setTotalFee(0);
			} else if (addOrderObj.getTotalFee().intValue() == 0 && (addOrderObj.getCashCoin().intValue() > 0 || addOrderObj.getBalancePaid().intValue() > 0)) {
				throw new PlatformException(ErrorEnum.C21212, ErrorEnum.C21212.getDesc());
			}
		} else {//无优惠，实付等于实付现金
			addOrderObj.setTotalFee(addOrderObj.getTotalPrice());
		}
		//计算妆币余额抵扣应付，运费可以被妆币、余额抵扣
		addOrderObj.setTotalFee(addOrderObj.getTotalFee().intValue() + addOrderObj.getFreight() - addOrderObj.getCashCoin() - addOrderObj.getBalancePaid());
		if (addOrderObj.getTotalFee().intValue() < 0) {//如果实付总金额小于0
			if (addOrderObj.getCashCoin().intValue() > 0 || addOrderObj.getBalancePaid().intValue() > 0) {//妆币或余额中有一个有大于0，提示用户余额或妆币食用过多
				throw new PlatformException(ErrorEnum.C21212, ErrorEnum.C21212.getDesc());
			} else {//没有使用余额妆币，抛出异常，理论上不会走到这一步
				logger.error("订单下单实付金额为负：{}-{}", addOrderObj.getTotalFee(), JSONObject.toJSONString(reqOrderDetail));
				throw new PlatformException(ErrorEnum.C20000, "订单生成异常，请稍候再试");
			}
		}
		if (addOrderObj.getTotalFee().intValue() == 0) {//0元付订单直接待发货
			addOrderObj.setStatus(OrderStatusEnum.S2.getCode());
			respAddOrderInfo.setPaid(true);//已支付
			addOrderObj.setPayTime(_now_time);
			addOrderObj.setPayId(addOrderObj.getOrderSn());
			//			orderObject.setPayType(PayTypeEnum.T25.getCode());
		} else {
			addOrderObj.setStatus(OrderStatusEnum.S1.getCode());
		}
		// orderObject.setCommisionFee(commisionFee);
		//设置交易订单店中店用户id
		if (_avl_goods_list.get(0).getTalentId() > 0) {
			addOrderObj.setOpenStoreUserId(_avl_goods_list.get(0).getTalentId());
		} else {
			addOrderObj.setOpenStoreUserId(_store_user.getUserId());
		}
		//生成交易订单
		int ooResult = orderDao.insertOrderObjectSelective(addOrderObj);
		if (ooResult != 1) {
			throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
		}
		//生成子单
		Map<Long, OrderInfo> orderInfoIdMap = new HashMap<Long, OrderInfo>();//以订单主键为索引的订单信息集合
		addOrderObj.getTotalFee();
		boolean isZeroOrder = addOrderObj.getTotalFee() == 0;//是否是0元单

		/*剩余金额*/
		long _total_surplus_discount_amount = userPromotion == null ? 0 : addOrderObj.getPromotionDiscount();//剩余总优惠金额
		long _total_surplus_xzb = addOrderObj.getCashCoin();//剩余总妆币
		long _total_surplus_ye = addOrderObj.getBalancePaid();//剩余总余额
		int _total_surplus_freight = addOrderObj.getFreight();//剩余总运费
		//云飞分摊妆币、余额
		long _total_surplus_freigth_xzb = 0;//剩余总云飞分摊妆币额
		long _total_surplus_freigth_ye = 0;//剩余云飞分摊余额额

		/*妆币、余额抵扣运费，扣除运费占用妆币、余额
		 * 扣除逻辑；1.先抵扣余额，再抵扣妆币*/
		if (addOrderObj.getFreight().intValue() > addOrderObj.getTotalFee() && (_total_surplus_xzb > 0 || _total_surplus_ye > 0)) {
			long _temp_total_freight = addOrderObj.getFreight().intValue() - addOrderObj.getTotalFee();
			if (_temp_total_freight <= _total_surplus_ye) {//余额抵扣运费
				_total_surplus_freigth_ye = _temp_total_freight;
				_total_surplus_ye -= _temp_total_freight;
			} else {
				_total_surplus_freigth_ye = _total_surplus_ye;
				_temp_total_freight -= _total_surplus_ye;
				_total_surplus_ye = 0;

				_total_surplus_freigth_xzb = _temp_total_freight;
				_total_surplus_xzb -= _temp_total_freight;
			}
		}
		//实际拆分妆币、余额
		long _dive_total_ye = _total_surplus_ye;
		long _dive_total_xzb = _total_surplus_xzb;

		long _dive_total_freigth_xzb = _total_surplus_freigth_xzb;
		long _dive_total_freigth_ye = _total_surplus_freigth_ye;

		//循环分组的商品明细、先生成自订单明细再生成自订单
		int i = k = orderVo.getStoreOrderDetails().size();//总自订单数：用于控制子订单运费精度
		for (int storeId : orderVo.getStoreOrderDetails().keySet()) {
			i--;

			StoreVo storeVo = brandService.getStoreById(storeId);
			OrderInfo addOrderInfo = new OrderInfo();
			addOrderInfo.setTotalFee(0);
			createOrderInfo(addOrderInfo, reqOrderDetail, storeVo, userAddress);
			addOrderInfo.setOrderObjectId(addOrderObj.getId());
			addOrderInfo.setStatus(addOrderObj.getStatus());
			addOrderInfo.setUserId(_login_user_id);
			addOrderInfo.setTotalPrice((int) orderVo.getStoreTotalAmount(storeId));

			double _order_info_rate = addOrderInfo.getTotalPrice().doubleValue() / addOrderObj.getTotalPrice();//子订单占总商品金额比例
			if (_total_surplus_freight > 0) {//有运费
				if (i == 0) {//最后一单，将剩余运费分到这一单
					addOrderInfo.setFreight(_total_surplus_freight);
				} else {//不是最后一个子订单，按精度四舍五入
					addOrderInfo.setFreight((int) Math.round(addOrderObj.getFreight() * _order_info_rate));
				}
				_total_surplus_freight -= addOrderInfo.getFreight();//计算剩余运费
			} else {
				addOrderInfo.setFreight(0);
			}
			//分摊妆币分摊云飞部分
			if (_total_surplus_freigth_xzb > 0) {
				if (i == 0) {
					addOrderInfo.setCashCoin((int) _total_surplus_freigth_xzb);
				} else {
					addOrderInfo.setCashCoin((int) Math.round(_dive_total_freigth_xzb * _order_info_rate));
				}
				_total_surplus_freigth_xzb -= addOrderInfo.getCashCoin();
			}
			//分摊余额分摊云飞部分
			if (_total_surplus_freigth_ye > 0) {
				if (i == 0) {
					addOrderInfo.setBalancePaid((int) _total_surplus_freigth_ye);
				} else {
					addOrderInfo.setBalancePaid((int) Math.round(_dive_total_freigth_ye * _order_info_rate));
				}
				_total_surplus_freigth_ye -= addOrderInfo.getBalancePaid();
			}

			List<OrderDetail> storeOrderDetails = orderVo.getStoreOrderDetails(storeId);
			int j = storeOrderDetails.size();
			for (OrderDetail orderDetail : storeOrderDetails) {
				j--;

				orderDetail.setStatus(addOrderObj.getStatus());
				orderDetail.setRecommendFrom(recommendFrom);//普通推荐人身份id
				orderDetail.setMemberRecommend(_login_user.getMemberRecommend());//会员推荐人
				orderDetail.setTalentTeacher(talentTeacher);//达人导师/经纪人身份id
				orderDetail.setTotalPrice(orderDetail.getSalePrice().intValue() * orderDetail.getQuantity());

				double _order_detail_rate = orderDetail.getTotalPrice().doubleValue() / addOrderObj.getTotalPrice();//商品行销售总价占整单销售总价比例
				//计算优惠，需要考虑优惠类型，品牌、商品、通用
				long _order_detail_discount_amount = 0;
				if (_total_surplus_discount_amount > 0) {
					if (i == 0 && j == 0) {//最后一个子订单，将剩余优惠分到次单上
						_order_detail_discount_amount = _total_surplus_discount_amount;
					} else {//不是最后一单，按优惠券类型分摊到行
						_order_detail_discount_amount = compODPomotionDiscount(userPromotion, orderDetail, orderVo);
					}
					_total_surplus_discount_amount -= _order_detail_discount_amount;//计算剩余优惠金额
				}
				//分摊妆币
				long _order_detail_xzb = 0;
				if (_total_surplus_xzb > 0) {
					if (i == 0 && j == 0) {//最后一单且最后一行时，剩余妆币分到最后一行
						_order_detail_xzb = _total_surplus_xzb;
					} else {//按比例分摊妆币
						_order_detail_xzb = Math.round(_dive_total_xzb * _order_detail_rate);
						if (_order_detail_xzb < 0) {//如果妆币为负数，赋值为0
							_order_detail_xzb = 0;
						}
					}
					_total_surplus_xzb -= _order_detail_xzb;//计算剩余可分妆币
				}
				//余额
				long _order_detail_ye = 0;
				if (_total_surplus_ye > 0) {
					if (i == 0 && j == 0) {//最后一单且最后一行时，剩余余额分到最后一行
						_order_detail_ye = _total_surplus_ye;
					} else {//按比例分摊余额
						_order_detail_ye = Math.round(_dive_total_ye * _order_detail_rate);
						if (_order_detail_ye < 0) {//余额为负数，赋值为0
							_order_detail_ye = 0;
						}
					}
					_total_surplus_ye -= _order_detail_ye;//计算剩余可分余额
				}
				//应付金额
				long _order_detail_total_fee = orderDetail.getTotalPrice().intValue() - _order_detail_discount_amount - _order_detail_xzb - _order_detail_ye;
				if (_order_detail_total_fee < 0) {//实付现金为负数
					if (_order_detail_xzb + _order_detail_ye + _order_detail_total_fee >= 0) {//当前分摊的妆币、余额总计>=当前实付现金（可抵扣）
						if (_order_detail_xzb + _order_detail_total_fee >= 0) {//精度分摊到妆币
							_order_detail_xzb += _order_detail_total_fee;
							_total_surplus_xzb -= _order_detail_total_fee;
						} else if (_order_detail_ye + _order_detail_total_fee >= 0) {//精度分摊到余额
							_order_detail_ye += _order_detail_total_fee;
							_total_surplus_ye -= _order_detail_total_fee;
						} else {//妆币、余额都小于负数，谁小就全额抵扣，剩余部分由大的补齐
							if (_order_detail_xzb > _order_detail_ye) {//妆币大于余额，实际分摊余额调整为0，剩余部分由妆币扣除
								_total_surplus_ye += _order_detail_ye;
								_order_detail_xzb += _order_detail_ye + _order_detail_total_fee;
								_total_surplus_xzb -= _order_detail_ye + _order_detail_total_fee;
								_order_detail_ye = 0;
							} else {//余额大于妆币，实际分摊妆币调整为0，剩余部分由余额扣除
								_total_surplus_xzb += _order_detail_xzb;
								_order_detail_ye += _order_detail_xzb + _order_detail_total_fee;
								_total_surplus_ye += _order_detail_xzb + _order_detail_total_fee;
								_order_detail_xzb = 0;
							}
						}
						_order_detail_total_fee = 0;
					} else {//商品妆币和余额总计不扣抵扣负数，抛出异常
						logger.error("{}-{}-{}", JSONObject.toJSONString(reqOrderDetail), JSONObject.toJSONString(orderDetail), _order_detail_total_fee);
						throw new PlatformException(ErrorEnum.C20000, "商品实付金额小于0");
					}
				}
				//0元付订单行应付现金不为0，调整妆币、余额使用量
				if (isZeroOrder && _order_detail_total_fee > 0) {
					if ((k > 1 && i > 0 || i == 0) && j > 0) {//不是最后一个子订单或子订单数为1并且不是最后一行
						if (_total_surplus_xzb + _total_surplus_ye > _order_detail_total_fee) {//能够从剩余妆币余额中扣减
							if (_total_surplus_xzb > _order_detail_total_fee && _total_surplus_ye > _order_detail_total_fee) {
								//剩余的可扣的妆币余额都大于多出的实付金额
								//妆币、余额两方均摊多出的实付金额
								long round = Math.round(_order_detail_total_fee / 2d);
								long afte = _order_detail_total_fee - round;
								if (_total_surplus_xzb > _total_surplus_ye) {//剩余妆币大于剩余余额，将分摊的大的从妆币扣除，小的从余额扣除
									if (round > afte) {
										_order_detail_xzb += round;
										_order_detail_ye += afte;
										_total_surplus_xzb -= round;
										_total_surplus_ye -= afte;
									} else {
										_order_detail_xzb += afte;
										_order_detail_ye += round;
										_total_surplus_xzb -= afte;
										_total_surplus_ye -= round;
									}
								} else {//剩余余额大于妆币，将分摊的大的从余额扣除，小的从妆币扣除
									if (round > afte) {
										_order_detail_xzb += afte;
										_order_detail_ye += round;
										_total_surplus_xzb -= afte;
										_total_surplus_ye -= round;
									} else {
										_order_detail_xzb += round;
										_order_detail_ye += afte;
										_total_surplus_xzb -= round;
										_total_surplus_ye -= afte;
									}
								}
							} else {
								if (_total_surplus_ye > _total_surplus_xzb) {//剩余余额大于剩余的妆币，妆币全部扣除，剩余多余支付的从余额扣除
									_order_detail_xzb += _total_surplus_xzb;
									_order_detail_ye += _order_detail_total_fee - _total_surplus_xzb;
									_total_surplus_ye -= _order_detail_total_fee - _total_surplus_xzb;
									_total_surplus_xzb = 0;
								} else {//剩余妆币大于剩余余额，余额全部扣除，剩余多于支付的从妆币扣除
									_order_detail_ye += _total_surplus_ye;
									_order_detail_xzb += _order_detail_total_fee - _total_surplus_ye;
									_total_surplus_xzb -= _order_detail_total_fee - _total_surplus_ye;
									_total_surplus_ye = 0;
								}
							}
							_order_detail_total_fee = 0;
						} else {
							logger.error("{}-{}-{}", JSONObject.toJSONString(reqOrderDetail), JSONObject.toJSONString(orderDetail), _order_detail_total_fee);
							throw new PlatformException(ErrorEnum.C20000, "0元付商品实付金额不等于0");
						}
					} else {//0元付订单最后一单，最后一行商品实付现金不为0
						logger.error("0元付订单最后一单，最后一行商品实付现金不为0:{}-{}-{}", JSONObject.toJSONString(reqOrderDetail), JSONObject.toJSONString(orderDetail), _order_detail_total_fee);
						throw new PlatformException(ErrorEnum.C20000, "0元付商品实付金额不等于0");
					}
				}

				if (_order_detail_total_fee < 0) {
					logger.error("{}-{}-{}", JSONObject.toJSONString(reqOrderDetail), JSONObject.toJSONString(orderDetail), _order_detail_total_fee);
					throw new PlatformException(ErrorEnum.C20000, "商品实付金额异常");
				}

				orderDetail.setCashCoin((int) _order_detail_xzb);
				orderDetail.setBalancePaid((int) _order_detail_ye);
				orderDetail.setPromotionDiscount((int) _order_detail_discount_amount);
				orderDetail.setTotalFee((int) _order_detail_total_fee);

				addOrderInfo.setCashCoin(addOrderInfo.getCashCoin().intValue() + orderDetail.getCashCoin());
				addOrderInfo.setBalancePaid(addOrderInfo.getBalancePaid().intValue() + orderDetail.getBalancePaid());
				addOrderInfo.setPromotionDiscount(addOrderInfo.getPromotionDiscount().intValue() + orderDetail.getPromotionDiscount());
			}

			if (addOrderInfo.getPromotionDiscount() > 0) {
				addOrderInfo.setPromotionId(addOrderObj.getPromotionId());
			}
			//计算子单应付现金
			addOrderInfo.setTotalFee(addOrderInfo.getTotalPrice() + addOrderInfo.getFreight().intValue() - addOrderInfo.getPromotionDiscount() - addOrderInfo.getCashCoin() - addOrderInfo.getBalancePaid());
			if (addOrderInfo.getTotalFee() < 0) {
				logger.error("拆单后子单应付小于0:{}-{}-{}", JSONObject.toJSONString(reqOrderDetail), JSONObject.toJSONString(addOrderInfo), addOrderInfo.getTotalFee());
				throw new PlatformException(ErrorEnum.C20000, "下单异常，请稍后再试");
			}

			orderDao.insertOrderInfoSelective(addOrderInfo);
			for (OrderDetail orderDetail : storeOrderDetails) {
				orderDetail.setOrderId(addOrderInfo.getId());
				orderDetail.setOrderObjectId(addOrderObj.getId());

				_subInventory(_login_user, orderDetail);
			}
			orderDao.batchInsertOrderDetail(storeOrderDetails);
			orderInfoIdMap.put(addOrderInfo.getId(), addOrderInfo);
		}
		if (_total_surplus_discount_amount != 0 || _total_surplus_xzb != 0 || _total_surplus_ye != 0) {
			logger.error("下单时妆币、余额或优惠券使用过多：{}-{}-{}:{}", _total_surplus_xzb, _total_surplus_ye, _total_surplus_discount_amount, JSONObject.toJSONString(reqOrderDetail));
			throw new PlatformException(ErrorEnum.C21212, ErrorEnum.C21212.getMessage());
		}
		if (_total_surplus_freight != 0) {
			logger.error("下单时运费分摊未完成：{}-{}", _total_surplus_freight, JSONObject.toJSONString(reqOrderDetail));
			throw new PlatformException(ErrorEnum.C21212, ErrorEnum.C21212.getMessage());
		}
		//生成自订单

		//生成子单明细
		//================================================================================/
		if (addOrderObj.getCashCoin() > 0 || addOrderObj.getBalancePaid() > 0) {
			List<CUserMoneyChange> _add_user_money_change_list = new LinkedList<>();
			if (addOrderObj.getCashCoin() > 0) {//记录现金币使用流水
				//扣除用户本次现金币
				if (respAddOrderInfo.isPaid()) {
					//直接扣减可用
					if (!userMoneyService.updateSubNormalAmount(_log_user_money.getXzb().getId(), _login_user_id, reqOrderDetail.getCashCoin())) {
						throw new PlatformException(ErrorEnum.C20125, "妆币不足");
					}
				} else {//扣减可用，增加冻结
					if (!userMoneyService.updateFreezeAmount(_log_user_money.getXzb().getId(), _login_user_id, reqOrderDetail.getCashCoin())) {
						throw new PlatformException(ErrorEnum.C20125, "妆币不足");
					}
				}
				MoneyBusinessType moneyBusinessType = moneyBusinessTypeService.selectMoneyBusinessByTypeIdForCache(14);
				if (moneyBusinessType != null) {
					//记录事务
					CUserPointTransaction addCUserPointTransaction = new CUserPointTransaction();
					addCUserPointTransaction.setUserId(_login_user_id);
					addCUserPointTransaction.setOrderSn(StringUtils.EMPTY);
					addCUserPointTransaction.setOrderDetailId(0l);
					addCUserPointTransaction.setOrderObjectId(addOrderObj.getId());
					addCUserPointTransaction.setBusinessSourceId(addOrderObj.getId());

					addCUserPointTransaction.setBusinessTypeId(moneyBusinessType.getTypeId());
					addCUserPointTransaction.setBusinessTypeName(moneyBusinessType.getTypeName());
					addCUserPointTransaction.setAmount(-addOrderObj.getCashCoin().longValue());
					addCUserPointTransaction.setIsCustom(0);//是否手工处理单据
					addCUserPointTransaction.setIsDelete(0);//是否删除 0 未删除 1已删除
					addCUserPointTransaction.setTransactionStatus(respAddOrderInfo.isPaid() ? 1 : -1);//已处理
					addCUserPointTransaction.setBusinessTime(new Date());
					addCUserPointTransaction.setCreatorId(_login_user_id);
					addCUserPointTransaction.setCreatorName(_login_user.getNickName());
					//保存
					cUserPointTransactionService.insertSelective(addCUserPointTransaction);

					// 记录用户资产的变化
					CUserMoneyChange addCUserMoneyChange = new CUserMoneyChange();
					_add_user_money_change_list.add(addCUserMoneyChange);

					addCUserMoneyChange.setCreatorId(_login_user_id);
					addCUserMoneyChange.setUserId(_login_user_id);
					addCUserMoneyChange.setOrderSn(addOrderObj.getId());// 源ID
					addCUserMoneyChange.setExtend1(addOrderObj.getOrderSn());

					addCUserMoneyChange.setChangeAmount(addCUserPointTransaction.getAmount().intValue());
					addCUserMoneyChange.setNormalBeforAmount(_log_user_money.getXzb().getAvailQuantity());
					addCUserMoneyChange.setFreeBeforAmount(_log_user_money.getXzb().getFrozenQuantity());
					addCUserMoneyChange.setSourceType(Byte.valueOf("2"));// 积分
					if (respAddOrderInfo.isPaid()) {//已支付
						addCUserMoneyChange.setChangeFreeAmount(0);
						//插入流水
						UserPointJournal addUserPointJournal = new UserPointJournal();
						addUserPointJournal.setOrderSn(StringUtils.EMPTY);
						addUserPointJournal.setOrderDetailId(0l);
						addUserPointJournal.setBusinessSourceId(addCUserPointTransaction.getId());//业务源单ID
						addUserPointJournal.setUserId(_login_user_id);//发生用户ID

						addUserPointJournal.setBusinessTypeId(moneyBusinessType.getTypeId());//业务类型ID
						addUserPointJournal.setBusinessTypeName(moneyBusinessType.getTypeName());//业务类型名称
						addUserPointJournal.setAmount(-addOrderObj.getCashCoin().longValue());//发生金额 允许负数
						addUserPointJournal.setIsCustom(0);//是否手工处理单据
						addUserPointJournal.setIsDelete(0);//是否删除 0 未删除 1已删除
						addUserPointJournal.setKeepAccountsType(moneyBusinessType.getKeepAccountsType());// 财务记账类型
						addUserPointJournal.setCreatorId(_login_user_id);
						addUserPointJournal.setCreatorName(_login_user.getNickName());
						userPointJournalService.addSelective(addUserPointJournal);
					} else {//未支付
						addCUserMoneyChange.setChangeFreeAmount(addOrderObj.getCashCoin());
					}
				}
			}
			if (addOrderObj.getBalancePaid() > 0) {
				//扣除余额
				if (respAddOrderInfo.isPaid()) {
					//直接扣除可用
					if (!userMoneyService.updateSubNormalAmount(_log_user_money.getBalance().getId(), _login_user_id, reqOrderDetail.getBalanceAmount())) {
						throw new PlatformException(ErrorEnum.C20125, ErrorEnum.C20125.getMessage());
					}
				} else {//扣除可用，增加冻结
					if (!userMoneyService.updateFreezeAmount(_log_user_money.getBalance().getId(), _login_user_id, reqOrderDetail.getBalanceAmount())) {
						throw new PlatformException(ErrorEnum.C20125, ErrorEnum.C20125.getMessage());
					}
				}

				MoneyBusinessType moneyBusinessType = moneyBusinessTypeService.selectMoneyBusinessByTypeIdForCache(5);
				if (moneyBusinessType != null) {
					//记录事务
					Commision commision = new Commision();
					commision.setOrderDetailId(0l);
					commision.setOrderInfoId(0l);
					commision.setOrderObjectId(addOrderObj.getId());
					commision.setUserId(_login_user_id);
					commision.setType(_login_user.getLevel());
					commision.setComment(moneyBusinessType.getTypeName());
					commision.setFee(-addOrderObj.getBalancePaid());
					commision.setSourceId(addOrderObj.getId());//源ID
					commision.setIsCustom(0);//是否手工
					if (respAddOrderInfo.isPaid()) {
						commision.setResult(1);//已处理
						commision.setStatus(1);//可用
						commision.setResultTime(_now_time);
					} else {
						commision.setResult(0);//未处理
						commision.setStatus(0);//禁用
					}
					commision.setBusinessTypeId(moneyBusinessType.getTypeId());//类型id
					commision.setBusinessTypeName(moneyBusinessType.getTypeName());//类型名字
					//保存
					commisionMapper.insertSelective(commision);
					// 记录用户资产的变化
					CUserMoneyChange addCUserMoneyChange = new CUserMoneyChange();
					_add_user_money_change_list.add(addCUserMoneyChange);

					addCUserMoneyChange.setCreatorId(_login_user_id);
					addCUserMoneyChange.setUserId(_login_user_id);
					addCUserMoneyChange.setOrderSn(addOrderObj.getId());// 源ID
					addCUserMoneyChange.setExtend1(addOrderObj.getOrderSn());
					addCUserMoneyChange.setChangeAmount(commision.getFee());
					addCUserMoneyChange.setNormalBeforAmount(_log_user_money.getBalance().getNormalAmount());
					addCUserMoneyChange.setFreeBeforAmount(_log_user_money.getBalance().getFrozenAmount());
					addCUserMoneyChange.setSourceType(Byte.valueOf("1"));// 余额

					if (respAddOrderInfo.isPaid()) {//已支付
						addCUserMoneyChange.setChangeFreeAmount(0);
						//插入流水
						UserJournal balanceJournal = new UserJournal();
						balanceJournal.setUserId(_login_user_id);
						balanceJournal.setCommisionId(commision.getId());
						balanceJournal.setOrderSn(addOrderObj.getOrderSn());
						balanceJournal.setPromotionDetailId(addOrderObj.getPromotionId());
						balanceJournal.setMoney(addOrderObj.getBalancePaid());
						balanceJournal.setComment(moneyBusinessType.getTypeName());
						balanceJournal.setStatus(UserJournalStatusEnum.S7.getCode());
						balanceJournal.setType(CommonConstants.USER_JOURNAL_TYPE_SUB);
						balanceJournal.setBusinessTypeId(moneyBusinessType.getTypeId());
						balanceJournal.setBusinessTypeName(moneyBusinessType.getTypeName());
						balanceJournal.setIsDelete(0);
						balanceJournal.setKeepAccountsType(moneyBusinessType.getKeepAccountsType());
						userJournalService.insertSelective(balanceJournal);
					} else {//未支付
						addCUserMoneyChange.setChangeFreeAmount(addOrderObj.getBalancePaid());
					}
				}
			}
			//记录变化日志
			saveUserMoneyChange(_login_user_id, _add_user_money_change_list);
		}
		//清除购物车
		shoppingCartService.updateRemoveShoppingCart(_login_user, addOrderObj.getId());

		//计算分佣
		addCommision(_login_user, addOrderObj, _check_inventory_map, orderInfoIdMap, baseRestrictionsMap);

		if (respAddOrderInfo.isPaid()) {//已支付推送oms
			//			XzOmsLog xzOmsLog = new XzOmsLog();
			//			xzOmsLog.setOrderSn(orderObject.getOrderSn());
			//			xzOmsLog.setOrderInfoSn(orderInfoList.get(0).getOrderSn());
			//			xzOmsLog.setResult("o元付订单");
			//			xzOmsLogService.insertSelective(xzOmsLog);
		} else {
			respAddOrderInfo.getPayTypeConfigList().addAll(getPayType(reqOrderDetail.getReqHeader().getPhoneType(), _login_user.isSalesman()));
		}
		respAddOrderInfo.setPayable(true);
		_avl_goods_list.clear();
		respAddOrderInfo.getErrorMsg().getAvlGoods().clear();
		return resultModel;
	}

	protected void createOrderObj(OrderObject orderObject, RequestOrderDetail reqOrderDetail, UserAddress userAddress) {
		orderObject.setCashCoin(reqOrderDetail.getCashCoin());
		orderObject.setBalancePaid(reqOrderDetail.getBalanceAmount());
		orderObject.setPromotionId(reqOrderDetail.getPromotionId());
		orderObject.setPayType(reqOrderDetail.getPayType());
		orderObject.setMemberDeliveryAddressId(reqOrderDetail.getMemberDeliveryAddressId());
		orderObject.setDeliveryWay(reqOrderDetail.getDeliveryWay());
		orderObject.setIsBill(reqOrderDetail.getIsBill());
		orderObject.setBillType(reqOrderDetail.getBillType());
		orderObject.setBillHeader(reqOrderDetail.getBillHeader());
		orderObject.setTaxpayerNo(reqOrderDetail.getBillTaxpayerNo());
		orderObject.setLinkMan(userAddress.getLinkMan());
		orderObject.setMobile(userAddress.getMobile());
		orderObject.setProvince(userAddress.getProvince());
		orderObject.setCity(userAddress.getCity());
		orderObject.setArea(userAddress.getArea());
		orderObject.setStreet(userAddress.getStreet());
		orderObject.setAddress(userAddress.getAddress());
		// orderObject.setLon(lon);
		// orderObject.setLat(lat);
		orderObject.setRemark(reqOrderDetail.getRemark());
		orderObject.setPayClientSource(reqOrderDetail.getReqHeader().getPhoneType());
	}

	private void createOrderInfo(OrderInfo orderInfo, RequestOrderDetail requestOrderDetail, StoreVo storeVo, UserAddress userAddress) {
		orderInfo.setOrderSn(OrderUtil.getOrderSn());
		orderInfo.setStoreId(storeVo.getStoreId());
		orderInfo.setStoreName(storeVo.getStoreName());
		orderInfo.setStoreProvince(storeVo.getProvince());
		orderInfo.setStoreCity(storeVo.getCity());
		orderInfo.setStoreArea(storeVo.getArea());
		orderInfo.setStoreAddress(storeVo.getAddress());
		orderInfo.setStoreLon(Double.valueOf(storeVo.getLon() != null ? storeVo.getLon() : "0.000000"));
		orderInfo.setStoreLat(Double.valueOf(storeVo.getLat() != null ? storeVo.getLat() : "0.000000"));
		orderInfo.setSettlementMan(storeVo.getSettlementMan());
		orderInfo.setSettlementAccount(storeVo.getSettlementAccount());
		orderInfo.setSettlementBank(storeVo.getSettlementBank());
		orderInfo.setPayType(requestOrderDetail.getPayType());
		orderInfo.setMemberDeliveryAddressId(requestOrderDetail.getMemberDeliveryAddressId());
		orderInfo.setDeliveryWay(requestOrderDetail.getDeliveryWay());
		orderInfo.setIsBill(requestOrderDetail.getIsBill());
		orderInfo.setBillType(requestOrderDetail.getBillType());
		orderInfo.setBillHeader(requestOrderDetail.getBillHeader());
		orderInfo.setTaxpayerNo(requestOrderDetail.getBillTaxpayerNo());
		orderInfo.setLinkMan(userAddress.getLinkMan());
		orderInfo.setMobile(userAddress.getMobile());
		orderInfo.setProvince(userAddress.getProvince());
		orderInfo.setCity(userAddress.getCity());
		orderInfo.setArea(userAddress.getArea());
		orderInfo.setStreet(userAddress.getStreet());
		orderInfo.setAddress(userAddress.getAddress());
		// orderInfo.setLon(lon);
		// orderInfo.setLat(lat);
		orderInfo.setRemark(requestOrderDetail.getRemark());
		orderInfo.setPointFee(0);
		orderInfo.setCommisionFee(0);
		orderInfo.setCashCoin(0);
		orderInfo.setBalancePaid(0);
		orderInfo.setPromotionDiscount(0);
	}

	/** 校验提交订单请求是否有效 */
	private boolean _check_avail_req_get_order_obj(RequestOrderDetail reqOrderDetail, ResponseResultModel<RespAddOrderInfo> resultModel, UserWalletVo userMoney) {
		if (StringUtils.isBlank(reqOrderDetail.getReqHeader().getPhoneType())) {
			resultModel.setError(ErrorEnum.C20102);
			resultModel.setMessage("phoneType is null");
			logger.warn("用户[{}]phoneType为空", reqOrderDetail.getUserId());
			return true;
		}
		if (reqOrderDetail.getMemberDeliveryAddressId() == null) {
			resultModel.setError(ErrorEnum.C20102);
			resultModel.setMessage("请设置收货地址");
			logger.warn("用户[{}]收货地址为空", reqOrderDetail.getUserId());
			return true;
		}

		if (reqOrderDetail.getIsBill() == 1) {//有发票
			if (reqOrderDetail.getBillType() == null) {
				resultModel.setError(ErrorEnum.C20102);
				resultModel.setMessage("请选择发票类型");
				logger.warn("用户[{}]发票类型为空", reqOrderDetail.getUserId());
				return true;
			} else {
				switch (reqOrderDetail.getBillType()) {
					case 2://公司
						if (StringUtils.isBlank(reqOrderDetail.getBillTaxpayerNo())) {
							resultModel.setError(ErrorEnum.C20102);
							resultModel.setMessage("请填写纳税人识别号");
							logger.warn("用户[{}]纳税人识别号为空", reqOrderDetail.getUserId());
							return true;
						}
					case 1://个人
						if (StringUtils.isBlank(reqOrderDetail.getBillHeader())) {
							resultModel.setError(ErrorEnum.C20102);
							resultModel.setMessage("请填写发票抬头");
							logger.warn("用户[{}]发票抬头为空", reqOrderDetail.getUserId());
							return true;
						}
						break;

					default:
						resultModel.setError(ErrorEnum.C20102);
						resultModel.setMessage("发票信息不全");
						logger.warn("用户[{}]填写发票信息不全", reqOrderDetail.getUserId());
						return true;
				}
			}
		}
		if (reqOrderDetail.getBalanceAmount() > 0) {
			//余额是否充足
			if (userMoney.getBalance().getNormalAmount() < reqOrderDetail.getBalanceAmount()) {
				resultModel.setError(ErrorEnum.C29901);
				resultModel.setMessage("余额不足");
				logger.warn("用户[{}]余额不足[{}-{}]", reqOrderDetail.getUserId(), userMoney.getBalance().getNormalAmount(), reqOrderDetail.getBalanceAmount());
				return true;
			}
			if (StringUtils.isBlank(reqOrderDetail.getPayPwd())) {
				resultModel.setError(ErrorEnum.C20102);
				resultModel.setMessage("支付密码为空");
				return true;
			}
			//校验支付密码
			UserPayInfo checkPayPwd = userPayInfoService.queryByUserId(reqOrderDetail.getUserId());
			if (checkPayPwd != null) {
				userMoney.setHasPayPwd(true);
				switch (checkPayPwd.getStatus()) {
					case 1:
						break;
					case 0:
					case 2:
						resultModel.setError(ErrorEnum.C25007);
						resultModel.setMessage("密码不可用，请重置密码");
						return true;
					default:
						resultModel.setError(ErrorEnum.C25007);
						resultModel.setMessage("密码不可用，请联系客服处理");
						return true;
				}
				if (!StringUtils.equals(reqOrderDetail.getPayPwd(), checkPayPwd.getPwd())) {
					resultModel.setError(ErrorEnum.C25007);
					resultModel.setMessage("密码错误");
					return true;
				} else {
					resultModel.getData().setPwdAvail(true);
				}
			} else {
				resultModel.setError(ErrorEnum.C25007);
				resultModel.setMessage("请设置支付密码");
				return true;
			}
		} else {
			userMoney.setHasPayPwd(userPayInfoService.existsPwd(reqOrderDetail.getUserId()));
			resultModel.getData().setPwdAvail(true);
		}
		//校妆币
		if (reqOrderDetail.getCashCoin() > 0) {
			if (userMoney.getXzb().getAvailQuantity() < reqOrderDetail.getCashCoin()) {
				resultModel.setError(ErrorEnum.C29901);
				resultModel.setMessage("妆币不足");
				logger.warn("用户[{}]余额不足[{}-{}]", reqOrderDetail.getUserId(), userMoney.getXzb().getAvailQuantity(), reqOrderDetail.getCashCoin());

				return true;
			}
		}
		return false;
	}

	/** 默认运费 */
	private int _get_default_freight() {
		return NumberUtils.toInt(Config.getString("orderFreight"), 0);
	}

	@Autowired
	private ShareGoodsMapper shareGoodsMapper;

	private boolean _check_share_goods_and_talent(GoodsSimpleVo req_goods, ResponseResultModel<RespGetOrderInfo3> resultModel) {
		if (req_goods == null) {
			return false;
		}
		long talentId = req_goods.getTalentId();
		long talentShareGoodId = req_goods.getTalentShareGoodId();
		if ((talentId == 0 && talentShareGoodId > 0) || (talentId > 0 && talentShareGoodId == 0)) {
			resultModel.setError(ErrorEnum.C20403);
			return true;
		} else if (talentId > 0 && talentShareGoodId > 0) {
			//为兼容tanlentShareGoodId新老接口传值不同：老接口是分享商品记录id新接口是商品ID的问题
			//1.首先判断分享记录与分享人与购买商品id是否一致，一致为老接口，否则为新接口
			ShareGoods _check_share_goods = shareGoodsMapper.selectShareGoodsById(talentShareGoodId);
			if (_check_share_goods == null || _check_share_goods.getUserId() != talentId || _check_share_goods.getGoodId() != req_goods.getGoodId()) {
				try {
					_check_share_goods = shareGoodsMapper.selectShareGoodsByUserIdAndGoodIdAndAgio(talentId, talentShareGoodId);
				} catch (Exception e) {
					logger.error("用户{}分享商品{}出现异常：{}", talentId, talentShareGoodId, e.getMessage());
				}
			}
			if (_check_share_goods == null || _check_share_goods.getUserId() != talentId || _check_share_goods.getGoodId() != req_goods.getGoodId()) {
				resultModel.setError(ErrorEnum.C20403);
				return true;
			}
			if (req_goods.getTalentShareGoodId() != _check_share_goods.getId()) {
				req_goods.setTalentShareGoodId(_check_share_goods.getId());//FIXME 设置分享商品id为分享商品记录id，保证老接口数据一致
			}
		}
		return false;
	}

	/** 校验分享人与分享商品 */
	private boolean _check_share_goods_and_talent(Long goodsId, long talentId, long talentShareGoodId, ResponseResultModel<?> resultModel) {
		if ((talentId == 0 && talentShareGoodId > 0) || (talentId > 0 && talentShareGoodId == 0)) {
			resultModel.setError(ErrorEnum.C20403);
			return true;
		} else if (talentId > 0 && talentShareGoodId > 0) {
			ShareGoods _check_share_goods = shareGoodsMapper.selectShareGoodsById(talentShareGoodId);
			if (_check_share_goods == null || talentId != _check_share_goods.getUserId() || goodsId != _check_share_goods.getGoodId()) {
				resultModel.setError(ErrorEnum.C20403);
				return true;
			}
		}
		return false;
	}

	@Override
	protected void setOpenStoreUser(RequestOrderDetail requestOrderDetail, ResponseUser user, OrderObject orderObject) {
		//购买商品为B区&&(用户推荐人身份id不为空||购买商品达人id不为空)
		if (requestOrderDetail.getOrderDetailList().get(0).getGoodsType() == GoodsTypeEnum.T1.getCode() && (user.getRecommendFrom() != null && !user.getRecommendFrom().isEmpty() || requestOrderDetail.getOrderDetailList().get(0).getTalentId().longValue() > 0)) {
			//以购买商品分享达人id为主，如果没有取当前用户推荐人
			if (requestOrderDetail.getOrderDetailList().get(0).getTalentId().longValue() == 0) {
				UserInfo userInfo = userService.selectUserInfoByPersionId(user.getRecommendFrom());
				if (userInfo != null) {
					orderObject.setOpenStoreUserId(userInfo.getUserId());
				}
			} else {
				orderObject.setOpenStoreUserId(requestOrderDetail.getOrderDetailList().get(0).getTalentId());
			}
		}
	}

	@Override
	protected void compOpenStoreDetailPrice(int experience, OrderObject orderObject, OrderDetail orderDetail, Map<Long, InventoryVo> inventoryMap) {
		//FIXME 是开店单且商品为自营商品(与去交易单时判断不一致，缺少判断商品是否属于b区，目前b、c区不能同时支付，不会出现C区自营商品进行开店首单优惠情况)
		if (orderObject.getOpenStore() != null && orderObject.getOpenStore().intValue() == 1 && inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport() == GoodsSelfTypeEnum.T0.getCode()) {
			inventoryMap.get(orderDetail.getInventoryId()).setSalePrice(inventoryMap.get(orderDetail.getInventoryId()).getSalePrice() * experience / 100);
		}
	}

	/** 返回开店优惠折扣，如果满足开店订单，标记订单为开店订单 */
	@Override
	protected int compOpenStorePrice(Map<String, BaseRestrictions> baseRestrictionsMap, int openStoreSelfFee, OrderObject orderObject) {
		int experience = baseRestrictionsMap.get(BaseRestrictionsEnum.T6.getText()).getExperience();
		if (openStoreSelfFee >= baseRestrictionsMap.get(BaseRestrictionsEnum.T6.getText()).getRestrictions()) {
			// orderObject.setTotalPrice(orderObject.getTotalPrice()-openStoreSelfFee+openStoreSelfFee*
			// baseRestrictionsMap.get(BaseRestrictionsEnum.T6.getText()).getExperience()/100);
			orderObject.setOpenStore(1);
		}
		return experience;
	}

	@Override
	protected OrderSettlement createOrderSettlement(Map<Long, OrderInfo> orderInfoIdMap, OrderDetail orderDetail, Map<Long, InventoryVo> inventoryMap, CompanyXz companyXz, boolean isSub, int currSettlementPriceDealer, int currCashCoinDealer, int currBalancePaidDealer) {
		OrderSettlement orderSettlement = createOrderSettlement(orderInfoIdMap, orderDetail, inventoryMap);
		orderSettlement.setGoodsType(orderDetail.getGoodsType());
		orderSettlement.setSelfSupport(inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport());

		orderSettlement.setSettlementRateDealer(inventoryMap.get(orderDetail.getInventoryId()).getSettlementRateDealer());
		orderSettlement.setSettlementRateManager(inventoryMap.get(orderDetail.getInventoryId()).getSettlementRateManager());

		orderSettlement.setSettlementPriceDealer((int) (Math.round((double) orderDetail.getTotalFee() * orderSettlement.getSettlementRateDealer() / 100)));
		orderSettlement.setCashCoinDealer((int) (Math.round((double) orderDetail.getCashCoin() * orderSettlement.getSettlementRateDealer() / 100)));
		orderSettlement.setBalancePaidDealer((int) (Math.round((double) orderDetail.getBalancePaid() * orderSettlement.getSettlementRateDealer() / 100)));

		orderSettlement.setSettlementPriceManager(orderDetail.getTotalFee() - orderSettlement.getSettlementPriceDealer());
		orderSettlement.setCashCoinManager(orderDetail.getCashCoin() - orderSettlement.getCashCoinDealer());
		orderSettlement.setBalancePaidManager(orderDetail.getBalancePaid() - orderSettlement.getBalancePaidDealer());
		return orderSettlement;
	}

	@Override
	protected int compOIPomotionDiscount(UserPromotion userPromotion, OrderObject orderObject, OrderInfo orderInfo, Map<String, Integer> oinfoBGSalePriceMap, Map<Integer, Integer> bgSalePriceMap) throws PlatformException {
		int promotionDiscount = 0;
		if (userPromotion == null) {//优惠券不存在，默认优惠抵扣为0
			return promotionDiscount;
		}
		switch (userPromotion.getType()) {
			case 1://现金币
						//				promotionDiscount = orderInfo.getTotalPrice().intValue() / orderObject.getTotalPrice() * orderObject.getPromotionDiscount();
					//				break;
			case 2://通用券
			case 7://自主券
				promotionDiscount = (int) (orderInfo.getTotalPrice().doubleValue() / orderObject.getTotalPrice() * orderObject.getPromotionDiscount());
				break;
			case 3://品牌券
				if (!oinfoBGSalePriceMap.containsKey(orderInfo.getStoreId() + "_" + userPromotion.getBrandId())) {
					orderInfo.setPromotionId(0);
					promotionDiscount = -1;
				} else {
					promotionDiscount = (int) (MapUtils.getDoubleValue(oinfoBGSalePriceMap, orderInfo.getStoreId() + "_" + userPromotion.getBrandId(), 0d) / bgSalePriceMap.get(userPromotion.getBrandId()) * orderObject.getPromotionDiscount());
				}
				break;
			case 5://商品券
				if (!oinfoBGSalePriceMap.containsKey(orderInfo.getStoreId() + "_" + userPromotion.getGoodId())) {
					orderInfo.setPromotionId(0);
					promotionDiscount = -1;
				} else {
					promotionDiscount = (int) (MapUtils.getDoubleValue(oinfoBGSalePriceMap, orderInfo.getStoreId() + "_" + userPromotion.getGoodId(), 0d) / bgSalePriceMap.get(userPromotion.getGoodId()) * orderObject.getPromotionDiscount());
				}
				break;
			default://优惠券不可用
				throw new PlatformException(ErrorEnum.C30110, ErrorEnum.C30110.getDesc());
		}
		return promotionDiscount;
	}

	/** 商品行优惠金额计算 */
	protected long compODPomotionDiscount(UserPromotionVo userPromotion, OrderDetail orderDetail, OrderAddParamsVo orderVo) {
		long promotionDiscount = 0;
		if (userPromotion == null || orderDetail.getIsOpenStoreGoods() == 1) {
			return promotionDiscount;
		}
		switch (userPromotion.getType()) {
			case 1://现金币
			case 2://通用券
			case 7://自主券
				promotionDiscount = Math.round(orderDetail.getTotalPrice().doubleValue() / orderVo.getTotalPrice() * userPromotion.getDiscountAmount());
				break;
			case 3://品牌券
				if (orderDetail.getBrandId().intValue() != userPromotion.getBrandId()) {
					promotionDiscount = 0;
				} else {
					promotionDiscount = Math.round(orderDetail.getTotalPrice().doubleValue() / orderVo.getBrandTotalAmount(userPromotion.getBrandId()) * userPromotion.getDiscountAmount());
				}
				break;
			case 5://商品券
				if (orderDetail.getGoodId().intValue() != userPromotion.getGoodId()) {
					promotionDiscount = 0;
				} else {
					promotionDiscount = Math.round(orderDetail.getTotalPrice().doubleValue() / orderVo.getGoodsTotalAmount(userPromotion.getGoodId()) * userPromotion.getDiscountAmount());
				}
				break;
		}
		return promotionDiscount;
	}

	@Override
	protected OpenStoreTypeEnum checkOpenStoreCommision(ResponseUser user, OrderObject orderObject, Map<String, ResponseUser> shareRecommendUserMap, Map<Long, ResponseUser> talentIdAndUserReMap, long talentId) {
		//首单且（存在普通推荐人身份或会员推荐人身份）
		if ((orderObject.getOpenStore() != null && orderObject.getOpenStore() == 1) && (shareRecommendUserMap.get(user.getRecommendFrom()) != null || talentIdAndUserReMap.get(talentId) != null)) {
			//			if (talentId == 0) {//不是达人分享
			//				if (shareRecommendUserMap.get(user.getRecommendFrom()).getLevel() == CommonConstants.TALENT_TEACHER_LEVEL) {//当前用户为讲师级别，讲师店
			//					return OpenStoreTypeEnum.T1;
			//				} else {//学生店
			//					return OpenStoreTypeEnum.T2;
			//				}
			//			} else {//达人商品
			//				if (talentIdAndUserReMap.get(talentId).getLevel() == CommonConstants.TALENT_TEACHER_LEVEL) {//达人为讲师级别
			//					return OpenStoreTypeEnum.T1;
			//				} else {//学生店
			//					return OpenStoreTypeEnum.T2;
			//				}
			//			}
			return OpenStoreTypeEnum.T2;
		} else {
			return OpenStoreTypeEnum.T0;
		}
	}

	@Override
	protected int openStoreCommision(OpenStoreTypeEnum openStoreTypeEnum, int commisionPrice, Map<String, BaseRestrictions> baseRestrictionsMap, int fee, Map<Long, InventoryVo> inventoryMap, OrderDetail orderDetail) {
		//商品是自营且店铺类型是学生店，计算分佣比例
		if (inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport() == GoodsSelfTypeEnum.T0.getCode() && openStoreTypeEnum.getCode() == OpenStoreTypeEnum.T2.getCode()) {
			fee = commisionPrice * baseRestrictionsMap.get(BaseRestrictionsEnum.T7.getText()).getExperience();
		}
		return fee;
	}

	@Override
	protected String openStoreComment(OpenStoreTypeEnum openStoreTypeEnum, String comment, Map<Long, InventoryVo> inventoryMap, OrderDetail orderDetail) {
		//商品是自营且开店店铺类型值大于0，标记为开店分佣
		if (inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport() == GoodsSelfTypeEnum.T0.getCode() && openStoreTypeEnum.getCode() > 0) {
			comment = CommonConstants.COMMISION_DESC_OPEN_STORE;
		}
		return comment;
	}

	@Override
	protected int openStoreCommision2(OpenStoreTypeEnum openStoreTypeEnum, int commisionPrice, Map<String, BaseRestrictions> baseRestrictionsMap, int fee, Map<Long, InventoryVo> inventoryMap, OrderDetail orderDetail) {
		//自主商品且是学生店
		if (inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport() == GoodsSelfTypeEnum.T0.getCode() && openStoreTypeEnum.getCode() == OpenStoreTypeEnum.T2.getCode()) {
			fee = commisionPrice * baseRestrictionsMap.get(BaseRestrictionsEnum.T7.getText()).getRestrictions();
		}
		return fee;
	}

	@Override
	protected void getUserPromotionOrderList(List<UserPromotionVo> userPromotionList, List<GoodsSimpleVo> goodsList) {
		int totalPrice = 0;
		Map<String, Integer> gbMap = new HashMap<String, Integer>();
		String goodsPrefix = "goods";
		String brandPrefix = "brand";
		boolean hasSelfGoods = false;
		boolean hasNoSelfGoods = false;
		for (GoodsSimpleVo goodsSimpleVo : goodsList) {
			if (!hasSelfGoods && goodsSimpleVo.getSelfSupport() == GoodsSelfTypeEnum.T0.getCode()) {
				hasSelfGoods = true;
			}
			if (!hasNoSelfGoods && goodsSimpleVo.getSelfSupport() == GoodsSelfTypeEnum.T1.getCode()) {
				hasNoSelfGoods = true;
			}
			String goodsKey = goodsPrefix + goodsSimpleVo.getGoodId();
			String brandKey = brandPrefix + goodsSimpleVo.getBrandId();
			if (gbMap.get(goodsKey) == null) {
				gbMap.put(goodsKey, goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity());
			} else {
				gbMap.put(goodsKey, goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity() + gbMap.get(goodsKey));
			}
			if (gbMap.get(brandKey) == null) {
				gbMap.put(brandKey, goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity());
			} else {
				gbMap.put(brandKey, goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity() + gbMap.get(brandKey));
			}
			totalPrice += goodsSimpleVo.getSalePrice() * goodsSimpleVo.getQuantity();
		}
		//		UserPromotionVo userPromotionTemp = null;
		//		int i = 0;
		List<UserPromotionVo> removeList = new ArrayList<UserPromotionVo>();
		for (UserPromotionVo userPromotion : userPromotionList) {
			switch (userPromotion.getType()) {
				case 1://妆币
					if (userPromotion.getLimited() > totalPrice) {
						removeList.add(userPromotion);
					} else {
						userPromotion.setDiscountAmount(userPromotion.getAmount());
						//						orderUserPromotionList(i, userPromotionTemp, userPromotion, userPromotionList);
					}
					break;
				case 2://现金券
					if (userPromotion.getLimited() > totalPrice) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getIsDiscount() == 0) {
							userPromotion.setDiscountAmount(userPromotion.getAmount());
						} else {
							userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * totalPrice / 100);
						}
						//						orderUserPromotionList(i, userPromotionTemp, userPromotion, userPromotionList);
					}
					break;
				case 3://品牌券
					if (gbMap.get(brandPrefix + userPromotion.getBrandId()) == null) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getLimited() > gbMap.get(brandPrefix + userPromotion.getBrandId())) {
							removeList.add(userPromotion);
						} else {
							if (userPromotion.getIsDiscount() == 0) {
								userPromotion.setDiscountAmount(userPromotion.getAmount());
							} else {
								userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * gbMap.get(brandPrefix + userPromotion.getBrandId()) / 100);
							}
							//							orderUserPromotionList(i, userPromotionTemp, userPromotion, userPromotionList);
						}
					}
					break;
				case 5://商品券
					if (gbMap.get(goodsPrefix + userPromotion.getGoodId()) == null) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getLimited() > gbMap.get(goodsPrefix + userPromotion.getGoodId())) {
							removeList.add(userPromotion);
						} else {
							if (userPromotion.getIsDiscount() == 0) {
								userPromotion.setDiscountAmount(userPromotion.getAmount());
							} else {
								userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * gbMap.get(goodsPrefix + userPromotion.getGoodId()) / 100);
							}
							//							orderUserPromotionList(i, userPromotionTemp, userPromotion, userPromotionList);
						}
					}
					break;
				case 7://自营非自营
					if (userPromotion.getLimited() > totalPrice) {
						removeList.add(userPromotion);
					} else if (userPromotion.getTargetSelfType() == GoodsSelfTypeEnum.T0.getCode() && hasNoSelfGoods || userPromotion.getTargetSelfType() == GoodsSelfTypeEnum.T1.getCode() && hasSelfGoods) {
						removeList.add(userPromotion);
					} else {
						if (userPromotion.getIsDiscount() == 0) {
							userPromotion.setDiscountAmount(userPromotion.getAmount());
						} else {
							userPromotion.setDiscountAmount((100 - userPromotion.getDiscount()) * totalPrice / 100);
						}
						//						orderUserPromotionList(i, userPromotionTemp, userPromotion, userPromotionList);
					}
					break;
				default://其它类型不可用
					removeList.add(userPromotion);
			}
			//			i++;
		}
		Collection<UserPromotionVo> existsAll = CollectionUtils.removeAll(userPromotionList, removeList);
		userPromotionList.clear();
		userPromotionList.addAll(existsAll);
		Collections.sort(userPromotionList, new UserPromotionComparator());
	}

	/** 封装异常商品 */
	private ErrorMsgGoods _pack_error_msg_goods(GoodsSimpleVo goodsSimpleVo, String errorMsg) {
		ErrorMsgGoods _add_err_goods = new ErrorMsgGoods();
		_add_err_goods.setGoodId(goodsSimpleVo.getGoodId());
		_add_err_goods.setGoodName(goodsSimpleVo.getGoodName());
		_add_err_goods.setSpecName(goodsSimpleVo.getSpecName());
		_add_err_goods.setGoodNavigateImage(goodsSimpleVo.getNavigateImg1());
		_add_err_goods.setInventoryId(goodsSimpleVo.getInventoryId());
		_add_err_goods.setSalePrice(goodsSimpleVo.getSalePrice());
		_add_err_goods.setProductPrice(goodsSimpleVo.getProductPrice());
		_add_err_goods.setMsg(errorMsg);
		if (CollectionUtils.isNotEmpty(goodsSimpleVo.getProductTags())) {
			_add_err_goods.getProductTags().addAll(goodsSimpleVo.getProductTags());
		}
		return _add_err_goods;
	}


	/** b区商品，只支持易宝支付，其它使用除易宝以外所有支付方式 */
	private List<PayTypeConfig> getPayType(String phoneType, boolean isTearcher) {
		return orderObjectService.queryOrderPayType(phoneType, isTearcher);
	}

	@Override
	public int updateOrderObjectPayUrlById(long id, String payUrl) {
		return 0;
	}

	@Override
	public String selectDivideString(Long orderDetailId) {
		return null;
	}

	@Override
	public void updateOrderObjectFreightNo(Long orderObjectId, String refundFeeNo) {}

	@Override
	public int selectDetailGoodsType(Long id) {
		return 0;
	}

	@Override
	public String selectSettlementAccount(Long orderObjectId) {
		return null;
	}

	@Override
	public List<String> selectOrderClearing() {
		return null;
	}

	@Override
	public void OrderSettlementartificialEliminate(List<String> orderObjectSn) {}

	@Override
	public List<User> selectOrderRecommendFromUser(Long id) {
		return null;
	}

}
